package com.example.springbootrabbitmq.demo6priority;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/*
  如果消息很少，优先级是没有意义的
  海量消息的时候，优先级才有意义
 */
@Component
public class PriorityMsgSender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public String send() {

        // 发送了优先级的消息
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务1", 1);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务1-2", 1);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务1-3", 1);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务1-4", 1);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务1-5", 1);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务2-5", 5);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务2-4", 5);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务2-3", 5);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务2-2", 5);
        sendPriorityMsg("priorExchange", "prior.queue", "测试优先级任务2-1", 5);
        return "success";
    }

    /*
    发送优先级的消息
    要求：队列要设置优先级参数x-max-priority
     */
    public void sendPriorityMsg(String exchange, String routeKey, Object msg, Integer priority) {
        MessagePostProcessor messagePostProcessor = message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            //设置编码
            messageProperties.setContentEncoding("utf-8");
            //设置过期时间10*1000毫秒
            messageProperties.setPriority(priority);
            return message;
        };
        rabbitTemplate.convertAndSend(exchange, routeKey, msg, messagePostProcessor);
    }
}
